#
# OpenSistemas::Zabbix::Sites
# Copyright (C) 2010 Open Sistemas <imasd@opensistemas.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#

# nt: sites it's an alias for groups
package OpenSistemas::Zabbix::Sites;

use strict;
use warnings;

use Carp;
use OpenSistemas::OID::Item;
use NetSNMP::ASN (':all');

use base 'OpenSistemas::OID::Tree';

my $siteName = '1.1.1.1';
my $siteID   = '1.1.1.2.1.1';
my $hostID   = '1.1.1.2.1.2';

sub new
{
	my ($pkg, %params) = @_;

  croak 'Sites: dhb parameter missing' if !exists ($params{dbh});
  croak 'Sites: baseOID parameter missing' if !exists ($params{baseOID});

	my $self = {
		%params
	};

	bless $self, $pkg;

	return $self;
}

sub update
{
  my $self = shift;
  my $dbh = $self->{dbh};
  my $i;

  my $sth = $dbh->prepare("select distinct g.name as siteID from groups g, hosts_groups hg, hosts h where hg.hostid=h.hostid and hg.groupid=g.groupid and h.status=0;");
  return 0 if !$sth;
  return 0 if !$sth->execute();
  $i = 0;
  while(my $ref = $sth->fetchrow_hashref())
  {
    $self->set(OpenSistemas::OID::Item->new({
      oid => $self->{baseOID} .'.' .$siteName .'.' .$i,
      asn => ASN_OCTET_STR,
      value => $ref->{siteID}
      }));
    $i++;
  }
  $sth->finish();

  $sth = $dbh->prepare("select g.name as siteID, h.host as hostID from groups g, hosts_groups hg, hosts h where hg.hostid=h.hostid and hg.groupid=g.groupid and h.status<>3;");
  return 0 if !$sth;
  return 0 if !$sth->execute();
  $i = 0;
  while(my $ref = $sth->fetchrow_hashref())
  {
    $self->set(OpenSistemas::OID::Item->new({
      oid => $self->{baseOID} .'.' .$siteID .'.' .$i,
      asn => ASN_OCTET_STR,
      value => $ref->{siteID}
      }));
    $self->set(OpenSistemas::OID::Item->new({
      oid => $self->{baseOID} .'.' .$hostID .'.' .$i,
      asn => ASN_OCTET_STR,
      value => $ref->{hostID}
      }));

    $i++;
  }
  $sth->finish();

  return 1;
}

1;
